import 'dart:ui' as ui show BoxHeightStyle, BoxWidthStyle;

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get.dart';

import 'rong_constant.dart';

/// <summary>
/// author：zwb
/// dateTime： 2021/12/14 15:41
/// filePath： lib/page/rong_im/util/rong_widget.dart
/// desc: 融云im 公共组件
/// <summary>
///
class RongWidget{

  static openDateTime(context,{DateTime? minDateTime,DateTime? maxDateTime,DateTime? initialDateTime,Function(DateTime)? onChange,Function(DateTime)? onConfirm}){
    DatePicker.showDatePicker(
      context,
      minDateTime: minDateTime ?? DateTime.parse("1900-01-01"),
      maxDateTime: maxDateTime ?? DateTime.now(),
      initialDateTime: initialDateTime ?? DateTime.now(),
      dateFormat: 'yyyy年-M月-d日',
      locale: DateTimePickerLocale.zh_cn,
      pickerTheme: DateTimePickerTheme(
          showTitle: true,
          confirmTextStyle: TextStyle(color: Colors.green)
      ),
      pickerMode: DateTimePickerMode.datetime,
      onCancel: () {
        debugPrint('onCancel');
      },
      onChange: (dateTime, List<int> index) {
        print(dateTime);
        if(onChange!=null) onChange(dateTime);
      },
      onConfirm: (dateTime, List<int> index) {
        print(dateTime);
        if(onConfirm!=null) onConfirm(dateTime);
      },
    );
  }

  /// todo：通用顶部导航
  /// AppBar仅能用于PreferredSizeWidget类型的场景 如：Scaffold 的 appBar
  static  appBarWidget({
    String? title,
    bool? centerTitle,
    List<Widget>? actions,
    double? elevation,
    Widget? leading,
    double? titleSize,
    Color? backgroundColor,
    Color? leftColor,
    Color? titleColor,
  }) {
    return AppBar(
      leading: leading ??
          InkWell(
            child: Icon(
              Icons.chevron_left,
              color: leftColor,
              size: 30,
            ),
            onTap: () => Get.back(),
          ),
      title: Text(
        title ?? '',
        style: TextStyle(
          fontSize: titleSize ?? 16,
          color: titleColor ?? Colors.black,
          fontWeight: FontWeight.bold
        ),
      ),
      centerTitle: centerTitle ?? true,
      actions: actions,
      elevation: elevation ?? 0.5,
      backgroundColor: backgroundColor,
    );
  }

  /// todo：基础的行组件
  static rowBaseWidget({
    String? leftText,
    String? rightText,
    String? subLeftText,
    bool showLine = true,
    bool showRightIcon = true,
    Function()? onTap,
    Widget? left,
    Widget? right,
    double? height,
    EdgeInsetsGeometry? padding,
    EdgeInsetsGeometry? margin,
    int rightFlex:1,
    int leftFlex:1,
    MainAxisAlignment? mainAxisAlignment,
    CrossAxisAlignment? crossAxisAlignment,
    Color? bgColor,
    int? maxLines,
  }){
    return Padding(padding: margin ?? EdgeInsets.all(0),child: Material(
      color: bgColor ?? Colors.white,
      child: InkWell(
        child: Container(
          padding: padding ?? EdgeInsets.symmetric(vertical: 18),
          height: height,
          decoration: BoxDecoration(
            border: Border(bottom: BorderSide(color: showLine ? Colors.grey.shade200 : Colors.transparent,width: 0.6),),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: crossAxisAlignment ?? CrossAxisAlignment.center,
            children: [
              left ?? Expanded(flex: leftFlex,child: Text("${leftText ?? ''}",style: TextStyle(color: Colors.black,fontSize: 14),),),
              right ?? Expanded(
                flex: rightFlex,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Expanded(child: Text("${rightText ?? ''}",style: TextStyle(color: Colors.grey.shade600,fontSize: 14),maxLines: maxLines ?? 2,overflow: TextOverflow.ellipsis,textAlign: TextAlign.end,),),
                    showRightIcon ? Icon(Icons.chevron_right,color:  Colors.grey.shade600,):SizedBox(),
                  ],
                ),
              ),
            ],
          ),
        ),
        onTap: onTap ?? null,
      ),
    ),);
  }

  /// todo: 渐变按钮
  static gradientButton(msg,{double? circular,Color? color,Function()? onTap,ShapeBorder? shape }){
    return Container(
      decoration: BoxDecoration(
        gradient: color!=null? null :const LinearGradient(colors: [
          Color(0xff79b00b),
          Color(0xff5f9608),
          Color(0xff4d8405),
        ],begin: Alignment.topCenter,end: Alignment.bottomCenter),
        borderRadius: BorderRadius.circular(circular ?? 4),
        color: color,
      ),
      child: MaterialButton(
        onPressed: (){
          if(onTap!=null) onTap();
        },
        child: RongWidget.text("$msg",color: Colors.white),
        color: Colors.transparent,
        elevation: 0,
        disabledElevation: 0,
        focusElevation: 0,
        hoverElevation: 0,
        highlightElevation: 0,
        minWidth: 100,
        shape: shape,
      ),
      height: 40,
    );
  }

  /// 空白 widget ，用于处理非法参数时的占位
  static Widget buildEmptyWidget() {
    return Container(
      height: 1,
      width: 1,
    );
  }

  /// 会话页面录音时的 widget，gif 动画
  static Widget buildVoiceRecorderWidget() {
    return Container(
      padding: EdgeInsets.fromLTRB(50, 0, 50, 200),
      alignment: Alignment.center,
      child: Container(
        width: 150,
        height: 150,
        child: Image.asset(RongConstant.getLocalImg("voice_recoder.gif")),
      ),
    );
  }

  static baseScaffoldWidget({Widget? child,bool loading:false,OnRefreshCallback? onRefresh,OnLoadCallback? onLoad}){
    // Header浮动
    bool _headerFloat = false;
    // 震动
    bool _vibration = true;
    return EasyRefresh(
      header: ClassicalHeader(
        enableInfiniteRefresh: false,
        infoColor: _headerFloat ? Colors.black87 : Colors.teal,
        float: _headerFloat,
        enableHapticFeedback: _vibration,
        refreshText: "拉动刷新",
        refreshReadyText: "释放刷新",
        refreshingText: "正在刷新...",
        refreshedText: "刷新完成",
        refreshFailedText: "刷新失败",
        noMoreText: "没有更多数据",
        infoText: "更新于 %T",
      ),   //头部刷新
      footer:ClassicalFooter(
        enableInfiniteLoad: false,
        enableHapticFeedback: _vibration,
        loadText: "拉动加载",
        loadReadyText: "释放加载",
        loadingText: "正在加载...",
        loadedText: "加载完成",
        loadFailedText: "加载失败",
        noMoreText: "没有更多数据",
        infoText: "",
        textColor: Colors.transparent,
      ),
      onRefresh: onRefresh ?? null,
      onLoad: onLoad ?? null,
      child: child,
    );
  }

  static Widget text(text,{Color? color,double? fonSize,double? height,FontWeight? fontWeight,Function()? onTap,int? maxLines}){
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: onTap ?? null,
        child: Text("${text ?? ''}",style: TextStyle(height: height,color: color,fontWeight: fontWeight,fontSize: fonSize,),maxLines: maxLines,overflow: TextOverflow.ellipsis,),
      ),
    );
  }

  static Widget title(text,{Color? color,double? fonSize,Function()? onTap,int? maxLines}){
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: onTap ?? null,
        child: Text("${text ?? ''}",style: TextStyle(color: color,fontWeight: FontWeight.bold,fontSize: fonSize,),maxLines: maxLines,overflow: TextOverflow.ellipsis,),
      ),
    );
  }

  static imgAsset(String imgName,{Color? color,EdgeInsetsGeometry? padding,double? width,double? height,Function()? onTap,BoxFit? fit}){
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: onTap ?? null,
        child: Padding(
          padding: padding ?? EdgeInsets.all(0),
          child:Image.asset(RongConstant.getLocalImg("$imgName"),color: color ,width: width,height: height,fit: fit,),
        ),
      ),
    );
  }

  static imgNet(String imgHostUrl,{EdgeInsetsGeometry? padding,double? width,double? height,bool size:false,bool clip:false,Function()? onTap,BoxFit? fit,BorderRadius? borderRadius}){
    // return  imgHostUrl == "" || imgHostUrl == "null"? SizedBox():
    return Padding(
      padding: padding ?? EdgeInsets.all(0),
      child: ClipRRect(
        borderRadius: borderRadius ?? BorderRadius.circular(clip ? width?? 0 : 0) ,
        child: Material(
          color: Colors.transparent,
          child: InkWell(
            onTap: onTap ?? null,
            child: CachedNetworkImage(
              imageUrl: imgHostUrl,width: width,height: size ? width:height,fit: fit ?? BoxFit.cover,
              progressIndicatorBuilder: (ctx,a,b){
                return CircularProgressIndicator(
                  color: Colors.green,
                  strokeWidth: 2,
                );
              },
              errorWidget: (ctx,url,err)  {
                return Center(child: Icon(Icons.error),);
              },
            ),
          ),
        ),
      ),
    );
  }

  static Widget rongInput({
    Key? key,
    TextEditingController? controller,
    FocusNode? focusNode,
    InputDecoration? decoration ,
    TextInputType? keyboardType,
    TextInputAction? textInputAction,
    TextCapitalization textCapitalization : TextCapitalization.none,
    TextStyle? style,
    StrutStyle? strutStyle,
    TextAlign textAlign : TextAlign.start,
    TextAlignVertical? textAlignVertical,
    TextDirection? textDirection,
    bool readOnly : false,
    ToolbarOptions? toolbarOptions,
    bool? showCursor,
    bool autofocus : false,
    obscuringCharacter : '•',
    bool obscureText : false,
    bool autocorrect : true,
    SmartDashesType? smartDashesType,
    SmartQuotesType? smartQuotesType,
    bool enableSuggestions : true,
    int? maxLines,
    int? minLines,
    bool expands : false,
    int? maxLength,
    bool maxLengthEnforced : true,
    Function(String)? onChanged,
    VoidCallback? onEditingComplete,
    Function(String)? onSubmitted,
    AppPrivateCommandCallback? onAppPrivateCommand,
    List<TextInputFormatter>? inputFormatters,
    bool? enabled,
    double? cursorWidth : 2.0,
    double? cursorHeight,
    Radius? cursorRadius,
    Color? cursorColor,
    ui.BoxHeightStyle selectionHeightStyle : ui.BoxHeightStyle.tight,
    ui.BoxWidthStyle selectionWidthStyle : ui.BoxWidthStyle.tight,
    Brightness? keyboardAppearance,
    EdgeInsets scrollPadding : const EdgeInsets.all(20.0),
    DragStartBehavior dragStartBehavior : DragStartBehavior.start,
    bool enableInteractiveSelection : true,
    Function()? onTap,
    MouseCursor? mouseCursor,
    InputCounterWidgetBuilder? buildCounter,
    ScrollController? scrollController,
    ScrollPhysics?  scrollPhysics,
    Iterable<String> ? autofillHints,
    String? restorationId,
    bool? isLeft,
    bool? isRight,
    Color? bgColor,
    double? height,
    EdgeInsetsGeometry? contentPadding,
    String? hintText,
    double? circular,
    Widget? icon,
    InputBorder? border,
    BoxBorder? boxBorder,
    Widget? suffixIcon,
    Widget? prefixIcon,
    TextStyle? hintStyle,
    Alignment? alignment,
    EdgeInsetsGeometry? boxPadding,
    Function()? onLongPress,
    GestureLongPressEndCallback? onLongPressEnd,
  }) {
    return GestureDetector(
      onTap: onTap,
      onLongPressEnd: onLongPressEnd,
      onLongPress: onLongPress,
      child: Container(
        decoration: BoxDecoration(
          color: bgColor ?? Color.fromRGBO(0, 0, 0, 0.04),
          border: boxBorder,
          borderRadius: BorderRadius.circular(circular ?? 20),
        ),
        alignment: alignment ?? Alignment.center,
        height: height == null || height < 35.0 ? 35 : height,
        padding: boxPadding,
        child: TextField(
          obscureText: obscureText,
          focusNode: focusNode,
          controller: controller,
          textAlign: textAlign,
          enabled: enabled,
          maxLength: maxLength,
          maxLines: maxLines,
          textInputAction: textInputAction,
          obscuringCharacter: obscuringCharacter,
          cursorColor: cursorColor ?? Color.fromRGBO(66, 133, 244, 1.0),
          // 对其 微调TextStyle的height 和 contentPadding
          style: style ?? TextStyle(height: 1.4,fontSize: 16,color: Colors.black87),
          inputFormatters: inputFormatters,
          decoration: InputDecoration(
              icon: icon,
              hintText: hintText,
              hintStyle: hintStyle,
              suffixIcon: suffixIcon,
              prefixIcon: prefixIcon,
              contentPadding: contentPadding ?? EdgeInsets.symmetric(vertical: 0,horizontal: 10),
              counterText: "",
              isCollapsed: true,
              border: InputBorder.none
          ),
          readOnly: readOnly,
          onChanged: onChanged,
          onSubmitted: onSubmitted,
          textAlignVertical: TextAlignVertical.center,
          keyboardType: keyboardType ?? TextInputType.text ,
          onTap: onTap,
        ),
      ),
    );
  }
}